package com.leetcode;

import com.leetcode.common.ListNode;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

/**
 * 19. 删除链表的倒数第 N 个结点
 * 堆栈法
 *
 * @author fy
 * @date 2022/4/11 16:13
 */
public class Solution19_1 {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummyHead = new ListNode(-1, head);
//        Stack<ListNode> stack = new Stack<>();
        Deque<ListNode> stack = new LinkedList<>();
        ListNode cur = dummyHead;
        while (cur != null) {
            stack.push(cur);
            cur = cur.next;
        }
        for (int i = 0; i < n; i++) {
            stack.pop();
        }
        ListNode pre = stack.peek();
        pre.next = pre.next.next;
        return dummyHead.next;
    }

}
